package com.ysstech.db.vcs.controller;

import com.ysstech.db.vcs.vo.LiquibaseRollbackReqVO;
import io.gitee.thghh.dynamic.liquibase.liquibase.DynamicSpringLiquibase;
import io.gitee.thghh.dynamic.liquibase.liquibase.DynamicSpringLiquibaseFactory;
import liquibase.exception.LiquibaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 控制器
 *
 * @author pengzhikang
 * @date 2024/11/28 16:59
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/liquibase")
public class LiquibaseController {

    @Autowired
    private DynamicSpringLiquibaseFactory springLiquibaseFactory;

    @PostMapping("/rollbackByTag")
    public ResponseEntity<String> rollbackByTag(@Validated @RequestBody LiquibaseRollbackReqVO reqVO) {
        DynamicSpringLiquibase springLiquibase = springLiquibaseFactory.getSpringLiquibase(reqVO.getLiquibaseType());
        if (springLiquibase == null) {
            String errorMessage = String.format("No Liquibase found for type: %s", reqVO.getLiquibaseType());
            log.warn(errorMessage);
            return new ResponseEntity<>(errorMessage, HttpStatus.NOT_FOUND);
        }

        try {
            springLiquibase.rollback(reqVO.getTag());
            return new ResponseEntity<>("Rollback successful", HttpStatus.OK);
        } catch (LiquibaseException e) {
            log.error("Error during rollback", e);
            return new ResponseEntity<>("Rollback failed", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}
